<template>
    <!-- 治疗开单 -->
    <div class="app-container">
        <div class="head-container">
            <div class="head-info">
                <div class="name">
                    <span>{{ patientInfo.patientName }}</span>
                </div>
                <div class="info">
                    <div>
                        {{ patientInfo.gender ? "男" : "女" }}
                    </div>
                    <div>{{ patientInfo.age }} 岁</div>
                    <div>{{ patientInfo.outpatientNum }}</div>
                </div>
            </div>
            <div class="head-btn">
                <el-button :type="showZQTYSOrCCYZ ? 'primary' : 'info'" size="mini" :disabled="!showZQTYSOrCCYZ"
                    @click="clickZQTYS">知情同意书</el-button>
                <el-button :type="showZQTYSOrCCYZ ? 'primary' : 'info'" size="mini" :disabled="!showZQTYSOrCCYZ"
                    @click="clickCCYZ">操舱医嘱</el-button>
                <el-button type="primary" size="mini" @click="clickSave">保存</el-button>
                <el-button type="primary" size="mini" @click="clickSubmit">提交</el-button>
            </div>
        </div>

        <div class="body">
            <div id="PatientList">
                <div class="search-container">
                    <el-input v-model="searchpatientName" placeholder="输入姓名查询"></el-input>
                    <el-button type="primary" size="mini" @click="searchName">查询</el-button>
                </div>
                <el-table :data="allpatientInfo" style="width: 200px" highlight-current-row @row-click="handleRowClick" :header-cell-style="{
                            background: '#eef1f6',
                            color: '#606266',
                        }" fit>
                    <el-table-column prop="patientName" label="患者姓名" />
                    <el-table-column prop="hisPatientId" label="hisId" />
                    <el-table-column prop="age" label="年龄" />
                    <el-table-column prop="gender" label="性别" :formatter="formatGender"/>
                </el-table>
                <el-pagination style="white-space: wrap;text-align: center;" :current-page="currentPage" :page-size="pageSize"
                    :page-sizes="[5, 10, 20, 30, 50]" :total="totalPatients" @current-change="handleCurrentChange"
                    @size-change="handleSizeChange" small
                    layout="prev, pager, next,total">
                </el-pagination>
            </div>
            <div id="left" :key="updateKey">
                <div class="changeBtn">
                    <button :class="{ bg: singleOrPlan }" @click="singleOrPlanChange">
                        治疗单项
                    </button>
                    <button :class="{ bg: !singleOrPlan }" @click="singleOrPlanChange">
                        治疗方案
                    </button>
                </div>

                <el-select v-model="itemType"  v-show="singleOrPlan" placeholder="项目类别" class="left-select" clearable @change="itemTypeChange">
                    <el-option v-for="item in itemTypeList" :key="item.itemCode" :label="item.itemName"
                        :value="item.itemId" />
                </el-select>

                <div class="left-search">
                    <el-input v-model="searchText" v-if="singleOrPlan" placeholder="项目名称/拼音代码" clearable />
                    <el-input v-model="searchText" v-else placeholder="方案名称/拼音代码" clearable />
                    <el-button type="primary" size="mini" @click="clickSearch">查询</el-button>
                </div>

                <el-table v-loading="loading" v-show="singleOrPlan" ref="cureSingle" :data="cureSingle"
                    style="width: 100%" height="660px" class="left-table" highlight-current-row :show-header="false"
                    @select="cureSingleChange">
                    <el-table-column prop="treatmentName" />
                    <el-table-column type="selection" width="55" />
                </el-table>

                <el-table v-show="!singleOrPlan" ref="curePlan" :data="curePlan" style="width: 100%" class="left-table"
                    highlight-current-row :show-header="false" @select="curePlanChange">
                    <el-table-column prop="programmeName" />
                    <el-table-column type="selection" width="55" />
                </el-table>
            </div>

            <div id="right">
                <div id="right-top">
                    <div id="right-top-info">
                        <div><strong>治疗项目明细</strong></div>
                        <div>
                            每次固定治疗时间: &nbsp;
                            <el-time-picker v-model="adviceTime" :default-value="new Date()" value-format="HH:mm"
                                format="HH:mm" class="width-120" />&nbsp;
                            <strong>总金额: &nbsp;&nbsp;<i>{{ totalMoney }}</i>元</strong>
                        </div>
                    </div>

                    <el-table :key="`${updateKey}detail`" :data="treatmentAdviceList" style="width: 100%" height="330" highlight-current-row
                        :header-cell-style="{
                            background: '#eef1f6',
                            color: '#606266',
                        }" fit>
                        <el-table-column type="index" label="序号" width="50" align="center">
                        </el-table-column>
                        <el-table-column label="自费" width="55" align="center">
                            <template #default="{ row }">
                                <el-checkbox size="mini" v-model="row.insuranceType" :true-label="0" :false-label="1"></el-checkbox>
                            </template>
                        </el-table-column>
                        <el-table-column prop="treatmentName" label="项目名称" align="center">
                            <template #default="{ row }">
                                {{ row.treatmentName }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="exePeriod" label="疗程" align="center">
                            <template #default="{ row }">
                               <el-input-number v-model="row.exePeriod" controls-position="right" :precision="0" :min="1"
                                    class="width-80" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="periodNum" label="疗程次数" align="center">
                            <template #default="{ row }">
                                <el-input-number v-model="row.periodNum" controls-position="right" :precision="0" :min="1"
                                    class="width-80" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="exeInterval" label="执行间隔" align="center">
                            <template #default="{ row }">
                                <el-input-number v-model="row.exeInterval" controls-position="right" :precision="0" :min="1"
                                    class="width-80" />&nbsp;天
                            </template>
                        </el-table-column>
                        <el-table-column label="单次数量" align="center">
                            <template #default="{ row }">
                                <el-input-number v-model="row.singleNum" controls-position="right" :precision="0" :min="1"
                                    class="width-80" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="dicItemUnitName" label="单位" align="center" />
                        <el-table-column prop="departmentName" label="执行科室" align="center" >
                            <template #default="{ row }">
                                {{ row.departmentName ? row.departmentName : row.exeDepartmentName }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="unitPrice" label="单价" align="center" />
                        <el-table-column prop="adviceId" label="医嘱ID" align="center" v-if="false" />
                        <el-table-column label="操作" align="center">
                            <template #default="{ row }">
                                <el-link type="danger" @click="delCureItemDetail(row)">删除</el-link>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>

                <div id="right-down">
                    <div id="right-down-info">
                        <div><strong>治疗评估</strong></div>
                    </div>

                    <el-table :data="estimateList" :key="`${updateKey}evaluate`" style="width: 100%" height="330" highlight-current-row
                        :header-cell-style="{
                            background: '#eef1f6',
                            color: '#606266',
                        }">
                        <el-table-column type="index" label="序号" align="center" fixed />

                        <el-table-column prop="estimateName" label="治疗评估表" align="center" />

                        <el-table-column prop="estimateStates" label="状态" align="center">
                            <template #default="{ row }">
                                <el-tag :type="row.estimateStates ? 'success' : 'warning'" effect="plain">
                                    {{ row.estimateStates ? "已评估" : "未评估" }}
                                </el-tag>
                            </template>
                        </el-table-column>

                        <el-table-column label="操作" align="center">
                            <template #default="{ row }">
                                <el-link type="primary" v-show="!row.estimateStates"
                                    @click="clickAssess(row)">评估</el-link>
                                <el-link type="success" v-show="row.estimateStates ||
                                    row.estimateId == 3 ||
                                    row.estimateId == 8 ||
                                    row.estimateId == 9
                                    " @click="clickDetail(row)">详情</el-link>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
        </div>

        <el-dialog :visible.sync="dialog.show" :width="dialog.width" destroy-on-close :close-on-click-modal="false"
            :show-close="false" top="5vh" :title="dialog.title">
            <informedConsent v-show="dialog.view == 'ZQTYS'" :patientInfo="patientInfo"
                :treatmentInformedInfo="treatmentInformedInfo" :fromHistory="fromHistory" @close="close">
            </informedConsent>
            <CCOrder v-show="dialog.view == 'CCYZ'" :adviceHyperbaricOxygen="adviceHyperbaricOxygen"
                :patientInfo="patientInfo" :fromHistory="fromHistory" @close="close"></CCOrder>
        </el-dialog>
    </div>
</template>

<script>
import {
    queryCureSingle,
    queryCurePlan,
    queryPlanItemList,
    dictionariesSearch,
    saveCureBilling,
    queryPatientInfo,
    commitCureBilling,
} from "@/api/residentPhysician/cureBilling.js";
import { sendAdviceQuery, sendInfoQuery } from "@/api/outpatient/medicalAdvice";
import informedConsent from "@/views/residentPhysician/informedConsent/index.vue";
import CCOrder from "@/views/residentPhysician/CCOrder/index.vue";
import { deepCopy } from "@/utils/tools.js";
import moment from 'moment';

//评定表path
const assessList = [
// {
//     name: "吞咽功能障碍评定",
//     editRoute:"SwallowTemplate",
//     detailRoute: "SwallowTemplate",
//     type: 1
//   },
//   {
//     name: "肺功能和日常生活评定表",
//     editRoute:"PulmonaryTemplate",
//     detailRoute: "PulmonaryTemplate",
//     type: 2
//   },
//   {
//     name: "周围性面神经炎治疗成绩评分表",
//     editRoute:"FacialNerveTemplate",
//     detailRoute: "FacialNerveTemplate",
//     type: 3
//   },
//   {
//     name: "初期康复评定记录表",
//     editRoute:"EarlyTemplate",
//     detailRoute: "EarlyTemplate",
//     type: 4
//   },
//   {
//     name: "中期康复评定记录表",
//     editRoute:"MidTermTemplate",
//     detailRoute: "MidTermTemplate",
//     type: 5
//   },
//   {
//     name: "出院前康复评定记录表",
//     editRoute:"DischargeTemplate",
//     detailRoute: "DischargeTemplate",
//     type: 6
//   },
//   {
//     name: "偏瘫运动功能评定表",
//     editRoute:"HemiplegiaTemplate",
//     detailRoute: "HemiplegiaTemplate",
//     type: 7
//   },
//   {
//     name: "神经损伤功能评定表",
//     editRoute:"NerveInjuryTemplate",
//     detailRoute: "NerveInjuryTemplate",
//     type: 8
//   },
//   {
//     name: "神经康复综合评定表",
//     editRoute:"NeurorehabilitationTemplate",
//     detailRoute: "NeurorehabilitationTemplate",
//     type: 9
//   },
//   {
//     name: "感知能力-耳聋分级",
//     editRoute:"DeafGradeTemplate",
//     detailRoute: "DeafGradeTemplate",
//     type: 10
//   },
//   {
//     name: "感知能力-程度评估",
//     editRoute:"DegreeTemplate",
//     detailRoute: "DegreeTemplate",
//     type: 11
//   },
//   {
//     name: "运动能力",
//     editRoute:"MotionTemplate",
//     detailRoute: "MotionTemplate",
//     type: 12
//   },
  {
    name: "针灸医疗记录单",
    editRoute:"acupunctureTemplate",
    detailRoute: "acupunctureTemplate",
    type: 13
  },
  {
    name: "康复治疗记录单",
    editRoute:"rehabRecordTemplate",
    detailRoute: "rehabRecordTemplate",
    type: 14
  },
  {
    name: "临床康复介入医疗记录单",
    editRoute:"clinicalRecordTemplate",
    detailRoute: "clinicalRecordTemplate",
    type: 15
  },
  {
    name: "滨江高压氧治疗的心理护理及安全告知书",
    editRoute:"hyperbaricNoticeBJTemplate",
    detailRoute: "hyperbaricNoticeBJTemplate",
    type: 16
  },
  {
    name: "高压氧治疗的心理护理及安全告知书",
    editRoute:"hyperbaricNoticeTemplate",
    detailRoute: "hyperbaricNoticeTemplate",
    type: 17
  },
  {
    name: "舱内治疗评估",
    editRoute:"chamberEvalTemplate",
    detailRoute: "chamberEvalTemplate",
    type: 18
  },
//   {
//     name: "MMSE 简易智能精神状态检查量表",
//     editRoute:"mmseScaleTemplate",
//     detailRoute: "mmseScaleTemplate",
//     type: 19
//   },
//   {
//     name: "焦虑自评量表(SAS)",
//     editRoute:"sasScaleTemplate",
//     detailRoute: "sasScaleTemplate",
//     type: 20
//   },
//   {
//     name: "抑郁自评量表",
//     editRoute:"sdScaleTemplate",
//     detailRoute: "sdScaleTemplate",
//     type: 21
//   },
//   {
//     name: "阿森斯失眠量表",
//     editRoute:"aisaScaleTemplate",
//     detailRoute: "aisaScaleTemplate",
//     type: 22
//   },
//   {
//     name: "9 条目患者健康问卷 (PHQ—9)",
//     editRoute:"phqQuestTemplate",
//     detailRoute: "phqQuestTemplate",
//     type: 23
//   },
//   {
//     name: "GAD—7 自评量表",
//     editRoute:"gadScaleTemplate",
//     detailRoute: "gadScaleTemplate",
//     type: 24
//   },
//   {
//     name: "症状自评量表(SCL-90)",
//     editRoute:"sclScaleTemplate",
//     detailRoute: "sclScaleTemplate",
//     type: 25
//   },
//   {
//     name: "SCL-90 测评纸",
//     editRoute:"sclPaperTemplate",
//     detailRoute: "sclPaperTemplate",
//     type: 26
//   },
//   {
//     name: "SCL-90 症状自评量表－简介",
//     editRoute:"sclCheckIntroTemplate",
//     detailRoute: "sclCheckIntroTemplate",
//     type: 27
//   },
//   {
//     name: "症状自评量表(SCL-90)使用说明",
//     editRoute:"sclinventoryTemplate",
//     detailRoute: "sclinventoryTemplate",
//     type: 28
//   },
//   {
//     name: "鼻炎熏蒸告知书",
//     editRoute:"rhiNoticeTemplate",
//     detailRoute: "rhiNoticeTemplate",
//     type: 29
//   },
//   {
//     name: "面部熏蒸告知书",
//     editRoute:"facialNoticeTemplate",
//     detailRoute: "facialNoticeTemplate",
//     type: 30
//   },
//   {
//     name: "眼部熏蒸告知书",
//     editRoute:"ocularFumigNoticeTemplate",
//     detailRoute: "ocularFumigNoticeTemplate",
//     type: 31
//   },
//   {
//     name: "熏蒸治疗单",
//     editRoute:"fumigRecTemplate",
//     detailRoute: "fumigRecTemplate",
//     type: 32
//   },
//   {
//     name: "督脉熏蒸治疗单",
//     editRoute:"duMeriRecTemplate",
//     detailRoute: "duMeriRecTemplate",
//     type: 33
//   },
//   {
//     name: "督脉熏蒸治疗告知书",
//     editRoute:"duMeriNoticeTemplate",
//     detailRoute: "duMeriNoticeTemplate",
//     type: 34
//   },
//   {
//     name: "腹直肌分离修复告知书",
//     editRoute:"rectusNoticeTemplate",
//     detailRoute: "rectusNoticeTemplate",
//     type: 35
//   },
//   {
//     name: "腹直肌治疗记录单",
//     editRoute:"rectusRecTemplate",
//     detailRoute: "rectusRecTemplate",
//     type: 36
//   },
//   {
//     name: "盆底检查报告单",
//     editRoute:"pelvicExaRepTemplate",
//     detailRoute: "pelvicExaRepTemplate",
//     type: 37
//   },
//   {
//     name: "盆底康复治疗单",
//     editRoute:"pelvicRehabRecTemplate",
//     detailRoute: "pelvicRehabRecTemplate",
//     type: 38,
//   },
//   {
//     name: "盆底康复治疗告知书",
//     editRoute:"pelvicRehabNoticeTemplate",
//     detailRoute: "pelvicRehabNoticeTemplate",
//     type: 39,
//   }
];

export default {
    data() {
        return {
            itemType: [], //项目类别
            itemTypeList: "",
            value: "",
            input: "",
            value1: "",
            singleOrPlan: true,
            fromHistory: false, //是否从历史治疗申请来
            treatmentIdList: [], //项目保存时，将该次保存的治疗单项ID保存在此，当提交时比对表格ID和提交时的数据组成的表格ID
            treatmentAdviceList: [], //治疗项目明细
            ReTreatmentAdviceList: [], // 保存历史治疗申请传递过来的原始治疗项目明细
            estimateList: [], //治疗评估
            ReEstimateList: [], // 保存历史治疗申请传递过来的原始治疗评估
            cureSingle: [], //治疗单项
            selectCureSingle: [], //已勾选的治疗单项
            curePlan: [], //治疗方案
            curePlanByItem: {}, //治疗方案对应的列表
            showZQTYSOrCCYZ: false,
            searchText: "", //搜索关键词
            loading: false,
            adviceTime: "", //治疗时间
            totalMoney: null, //总金额
            patientInfo: {}, //病人信息
            allpatientInfo: [],  //病人信息
            batchIdData: {
                batchId: null,
            }, //提交时用的批号信息
            dialog: {
                //dialog相关参数
                show: false,
                width: "60%",
                view: "",
                title: "",
            },
            treatmentInformedInfo: {
                //治疗知情同意书参数
                signName: "",
                treatmentTarget: [],
                dicPatientRelation: "",
                coreRisk: [],
                fingerprint: "",
                signTime:'',
            },
            adviceHyperbaricOxygen: {
                //操舱医嘱参数
                adviceNote: "",
                gaugePressure: null,
                singleOxygenMinute: null,
                singleOxygenNum: null,
                intervalOxygenMinute: null,
                intervalOxygenNum: null,
                exePeriod: null,
                periodNum: null,
                doctorSign: "",
                curativeEffect: [],
                treatmentInterruptionReason: [],
                briefCondition: "",
            },
            currentPage: 1, // 当前页码
            pageSize: 10,  // 每页显示数量
            totalPatients: 0, // 总患者数
            searchpatientName: "", //查询患者
            updateKey: 0, // 刷新key
        };
    },
    components: {
        informedConsent,
        CCOrder,
    },
    computed: {
        batchId() {
            return this.$route.params.batchId;
        },
        isReviseBtn() {
            return this.$store.state.common.isReviseBtn;
        },
    },
    methods: {
        //关闭dialog
        close() {
            this.dialog = {
                show: false,
                width: "60%",
                view: "",
                title: "",
            };
        },
        //判断两个数组是否相等
        arraysAreEqual(arr1, arr2) {
            if (arr1.length !== arr2.length) {
                return false;
            }

            for (let i = 0; i < arr1.length; i++) {
                if (arr1[i] !== arr2[i]) {
                    return false;
                }
            }

            return true;
        },
        //左侧患者列表点击查询
        searchName() {
            this.getAllPatientInfo()
        },
        //查询患者信息
        getPatientInfo(hisPatientId) {
            let params = {
                page: 1,
                size: 10,
                hisPatientId: hisPatientId,
                patientType: 1,
            };
            queryPatientInfo(params)
                .then((response) => {
                    let { code, content } = response;
                    if (code === 0 && content) {
                        this.patientInfo = content[0];
                    } else {
                        this.patientInfo = {};
                    }
                })
                .catch((error) => {
                    console.log(error);
                    this.$notify({
                        title: "提示",
                        message: "网络出差了,请稍后再试",
                        type: "danger",
                    });
                });
        },
        //患者信息
        getAllPatientInfo() {
            let params = {
                page: this.currentPage,
                size: this.pageSize,
                patientName: this.searchpatientName || "",
                patientType: 1,
            }
            queryPatientInfo(params).then(response => {
                let { code, content, totalElements } = response;
                if (code === 0 && content) {
                    this.allpatientInfo = content;
                    this.totalPatients = totalElements;
                    console.log(this.allpatientInfo, "this.allpatientInfo");
                } else {
                    this.allpatientInfo = {};
                }
            }).catch(error => {
                console.log(error);
                this.$notify({
                    title: '提示',
                    message: '网络出差了,请稍后再试',
                    type: 'danger'
                });
            })
        },
        // 处理每页显示条数变化的逻辑
        handleSizeChange(val) {
            this.pageSize = val;
            this.getAllPatientInfo();
        },
        // 处理当前页码变化的逻辑
        handleCurrentChange(val) {
            this.currentPage = val;
            this.getAllPatientInfo();
        },
        handleRowClick(row) {
            const hisPatientId = row.hisPatientId;
            this.getPatientInfo(hisPatientId);
            this.clearViewData();
        },
        clearViewData(){
            this.treatmentAdviceList = [];
            this.estimateList = [];
            // this.cureSingle = [];
            this.updateKey = Math.random();
        },
        //选择自费还是医保提示
        selfPayTip(row) {
            if (row.insuranceLimitDesc) {
                this.$confirm(
                    `${row.treatmentName} 存在医保限制，原因是：限严重缺氧性疾病、严重脑外伤、突发性耳聋、放射性脑病、特殊气体中毒或潜水病，请选择自费或医保？`,
                    "提示",
                    {
                        confirmButtonText: "自费",
                        cancelButtonText: "医保",
                        type: "warning",
                        closeOnClickModal: false,
                    }
                )
                    .then(() => {
                        row.insuranceType = 0;
                    })
                    .catch(() => {
                          row.insuranceType = 1;
                    });
            }
        },

        //获取治疗单项
        getCureSingle(obj = {}) {
            this.loading = true;
            let params = {
                page: 1,
                size: 9999,
                useType: '1,3'
            }
            if (Object.keys(obj).length) {
                params = Object.assign(params, obj);
            }
            queryCureSingle(params)
                .then((response) => {
                    let { code, content } = response;
                    if (code === 0 && content) {
                        content.forEach((item) => {
                            item.insuranceType = 1;
                            item.singleNum = 1;
                        });
                        this.cureSingle = content.filter((item) => {
                            return item.useType !== 2;
                        });
                        this.cureSingle = this.cureSingle.filter((item) => {
                            return item.treatmentStates == 0;
                        });
                        //如果是从历史治疗申请跳转过来 如果有治疗项目明细 左侧治疗项目列表做勾选
                        this.batchId &&
                            this.treatmentAdviceList &&
                            this.treatmentAdviceList.forEach((item) => {
                                let sinleItem = this.cureSingle.find(
                                    (val) => val.treatmentId == item.treatmentId
                                );
                                this.$nextTick(() => {
                                    sinleItem &&
                                        this.$refs.cureSingle.toggleRowSelection(sinleItem, true);
                                });
                            });
                    } else {
                        this.cureSingle = [];
                    }
                })
                .catch((err) => {
                    console.log(err);
                })
                .finally(() => {
                    setTimeout(() => {
                        this.loading = false;
                    }, 300);
                });
        },
        //获取治疗方案
        getCurePlan(obj = {}) {
            //定义参数
            let params = {
                page: 1,
                size: 10,
                programmeStates: 1,
            }
            //如果有传入参数，则合并参数
            if (Object.keys(obj).length) {
                params = Object.assign(params, obj)
            }
            //查询治疗方案
            queryCurePlan(params)
                //成功
                .then((response) => {
                    let { code, content } = response;
                    if (code === 0 && content) {
                        //筛选出状态为1的治疗方案
                        this.curePlan = content.filter((item) => {
                            return item.programmeStates == 1;
                        });
                    } else {
                        //没有数据
                        this.curePlan = [];
                    }
                })
                //失败
                .catch((err) => {
                    console.log(err);
                });
        },

        //治疗单项治疗方案切换钩子
        singleOrPlanChange() {
            this.singleOrPlan = !this.singleOrPlan;
            this.searchText = '';
            if (this.treatmentAdviceList.length) {
                this.treatmentAdviceList.forEach((item) => {
                    let sinleItem = this.cureSingle.find(
                        (val) => val.treatmentId == item.treatmentId
                    );
                    this.$nextTick(() => {
                        sinleItem &&
                            this.$refs.cureSingle.toggleRowSelection(sinleItem, true);
                    });
                });
            } else {
                this.$refs.cureSingle.clearSelection();
            }
        },
        //治疗单项勾选时
        cureSingleChange(value, row) {
            this.treatmentAdviceList = value;
            //当从历史治疗申请中点击进入时
            if (this.$route.params.batchId) {
                //遍历历史治疗申请中的数据
                this.ReTreatmentAdviceList.forEach((item) => {
                    //在当前治疗申请中查找对应的数据
                    const index = this.treatmentAdviceList.findIndex((data) => {
                        return data.treatmentId === item.treatmentId;
                    });
                    //如果找到对应的数据
                    if (index !== -1) {
                        //将历史治疗申请给当前治疗申请
                        this.treatmentAdviceList[index] = item;
                    }
                });

                //如果当前治疗申请中的数据数量大于或等于历史治疗申请中的数据数量
                if (value.length >= this.treatmentAdviceList.length) {
                    //遍历历史治疗申请中的数据，将其添加到当前治疗申请
                    value.forEach((item) => {
                        this.treatmentAdviceList.push(item);
                    });
                    //调用方法，重新排序
                    this.cureItemDetailFilter();
                //如果当前治疗申请中的数据数量小于历史治疗申请中的数据数量
                } else {
                    //遍历历史治疗申请中的数据，找出当前治疗申请中存在的数据
                    let arr = [];
                    value.forEach((item) => {
                        let a = this.treatmentAdviceList.find((data) => {
                            return data.treatmentId == item.treatmentId;
                        });
                        //如果找到对应的数据
                        if (!(a == undefined)) {
                            arr.push(a);
                        }
                    });
                    //将当前治疗申请中的数据设置为arr
                    this.treatmentAdviceList = arr;
                }
            }

            if (!value.length) {
                this.estimateList = [];
            } else {
                if (value.find((item) => item === row)) {
                    this.selfPayTip(row);
                }
            }
            //判断是否显示知情同意书和操仓医嘱
            this.showZQTYSOrCCYZ = value.find((item) => item.highOxygenStates == 1)
                ? true
                : false;
            this.initCureAssess(value);
        },

        //初始化治疗评估列表
        initCureAssess(value) {
            this.estimateList = [];
            value.forEach((item) => {
                if (item.treatmentEstimate) {
                    item.treatmentEstimate.forEach((item2) => {
                        if (
                            !this.estimateList.find(
                                (item3) => item3.estimateId == item2.estimateId
                            )
                        ) {
                            this.estimateList.push(item2);
                        }
                    });
                }
            });
            if (this.$route.params.batchId) {
                this.ReEstimateList.forEach((item) => {
                    const index = this.estimateList.findIndex((data) => {
                        return data.estimateId === item.estimateId;
                    });
                    if (index !== -1) {
                        this.estimateList[index].estimateStates = item.estimateStates;
                    }
                });
            }
        },
        //治疗方案勾选时
        curePlanChange(value, row) {
            let { programmeId } = row;
            //勾选时取获取治疗单项
            if (value.find((item) => item.programmeId === programmeId)) {
                this.getPlanItemList(programmeId);
            } else {
                //取消勾选时判断治疗项目明细中项目是否删除
                this.treatmentAdviceList = this.treatmentAdviceList.filter(
                    (item) => item.programmeId !== programmeId
                );
                delete this.curePlanByItem[programmeId];
                for (let key in this.curePlanByItem) {
                    this.treatmentAdviceList = [
                        ...this.treatmentAdviceList,
                        ...this.curePlanByItem[key],
                    ];
                }
                this.cureItemDetailFilter();
            }
            //判断是否显示知情同意书和操仓医嘱
            this.showZQTYSOrCCYZ = this.treatmentAdviceList.find(
                item => item.highOxygenStates == 1
            )
                ? true
                : false;
        },

        //根据治疗方案获取项目列表
        getPlanItemList(programmeId) {
            let params = {
                page: 1,
                size: 30,
                programmeId,
                queryPage: 1,
            };
            queryPlanItemList(params)
                .then((response) => {
                    let { code, content } = response;
                    if (code === 0 && content) {
                        content.forEach((item) => {
                            item.insuranceType = 1;
                            this.selfPayTip(item);
                            this.treatmentAdviceList.push(item);
                        });
                        !this.curePlanByItem[programmeId] &&
                            (this.curePlanByItem[programmeId] = [...content]);
                        this.cureItemDetailFilter();
                    }
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        //查询项目类别
        getItemType() {
            let params = {
                dicCode: "dicItemCategory",
            };
            dictionariesSearch(params)
                .then((response) => {
                    let { code, content } = response;
                    if (code === 0 && content) {
                        this.itemTypeList = content[0].itemList;
                    } else {
                        this.itemTypeList = [];
                    }
                })
                .catch((err) => {
                    console.log(err);
                });
        },

        //项目类别选择时
        itemTypeChange(value) {
            this.getCureSingle({
                dicItemCategory: value,
            });
        },

        //治疗单项明细去重
        cureItemDetailFilter() {
            let arr = [];
            this.treatmentAdviceList.forEach((item) => {
                if (!arr.find((val) => val.treatmentId === item.treatmentId)) {
                    arr.push(item);
                }
            });
            //判断是否显示知情同意书和操仓医嘱
            this.showZQTYSOrCCYZ = arr.find((item) => item.highOxygenStates == 1)
                ? true
                : false;
            this.treatmentAdviceList = arr;
            this.initCureAssess(this.treatmentAdviceList);
        },

        // 点击删除治疗单项
        delCureItemDetail(row) {
            if (this.singleOrPlan) {
                this.$confirm("是否确定删除该条项目?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                    closeOnClickModal: false,
                }).then(() => {
                    this.$nextTick(() => {
                        let delTarget = this.cureSingle.find(
                            (item) => item.treatmentId == row.treatmentId
                        );
                        this.$refs.cureSingle.toggleRowSelection(delTarget, false);
                        this.treatmentAdviceList = this.treatmentAdviceList.filter(
                            (item) => item !== row
                        );
                        this.initCureAssess(this.treatmentAdviceList);
                    });
                })
                    .catch(() => {
                        javascript: ;
                    });
            }
            //判断是否显示知情同意书和操仓医嘱
            this.showZQTYSOrCCYZ = this.treatmentAdviceList.find(
                (item) => item.highOxygenStates == 1
            )
                ? true
                : false;
        },
        //点击查询
        clickSearch() {
            let text = this.singleOrPlan ? '请输入项目名称或者拼音代码' : '请输入方案名称或者拼音代码';
            if (!this.searchText) {
                this.$notify({
                    title: "提示",
                    message: text,
                    type: "warning",
                });
                return;
            }
            if (this.singleOrPlan) {
                this.getCureSingle({
                    treatmentNameOrRef: this.searchText
                });
            } else {
                this.getCurePlan({
                    programmeNameOrRef: this.searchText
                })
            }
        },
        //点击知情同意书
        clickZQTYS() {
            this.dialog = {
                show: true,
                width: "50%",
                view: "ZQTYS",
                title: "知情同意书",
            };
        },
        //点击操舱医嘱
        clickCCYZ() {
            this.dialog = {
                show: true,
                width: "50%",
                view: "CCYZ",
                title: "操舱医嘱",
            };
        },

        //点击保存
        clickSave() {
            //判断知情同意书和操舱医嘱是否填写
            if (this.showZQTYSOrCCYZ) {
                if (!this.treatmentInformedInfo.isSave) {
                    this.$notify({
                        title: "提示",
                        message: "请填写知情同意书后在保存",
                        type: "warning",
                    });
                    return;
                }
                if (!this.adviceHyperbaricOxygen.isSave) {
                    this.$notify({
                        title: "提示",
                        message: "请填写操舱医嘱后在保存",
                        type: "warning",
                    });
                    return;
                }
            }
            if (!this.treatmentAdviceList.length) {
                this.$notify({
                    title: "提示",
                    message: "请选择治疗单项或治疗方案",
                    type: "warning",
                });
                return;
            }
            if (!this.adviceTime) {
                this.$notify({
                    title: "提示",
                    message: "请填写治疗时间",
                    type: "warning",
                });
                return;
            }

            let { patientId, hisPatientId } = this.patientInfo;
            //处理治疗医嘱列表参数
            let treatmentAdviceList = [];

            this.treatmentAdviceList.forEach((item) => {
                let {
                    treatmentId,
                    insuranceType,
                    exePeriod,
                    periodNum,
                    exeInterval,
                    singleNum,
                    adviceId,
                } = item;
                treatmentAdviceList.push({
                    treatmentId,
                    insuranceType,
                    exePeriod,
                    periodNum,
                    exeInterval,
                    singleNum,
                    adviceId,
                });
            });

            //处理知情同意书参数
            let treatmentInformedInfo = deepCopy(this.treatmentInformedInfo);
            treatmentInformedInfo.signTime=moment(treatmentInformedInfo.signTime).format('x')
            if (Array.isArray(treatmentInformedInfo.coreRisk)) {
                treatmentInformedInfo.coreRisk =
                    treatmentInformedInfo.coreRisk.join(",");
            }
            if (Array.isArray(treatmentInformedInfo.treatmentTarget)) {
                treatmentInformedInfo.treatmentTarget =
                    treatmentInformedInfo.treatmentTarget.join(",");
            }

            let data = {};

            if (this.showZQTYSOrCCYZ) {
                data = {
                    patientId,
                    hisPatientId,
                    adviceTime: this.adviceTime,
                    treatmentAdviceList, //治疗医嘱列表
                    treatmentInformedInfo, //治疗知情同意书
                    adviceHyperbaricOxygen: this.adviceHyperbaricOxygen, //高压氧操舱医嘱
                    // estimateList, //评估列表
                };
            } else {
                data = {
                    patientId,
                    hisPatientId,
                    adviceTime: this.adviceTime,
                    treatmentAdviceList, //治疗医嘱列表
                    // estimateList, //评估列表
                };
            }

            saveCureBilling(data)
                .then((response) => {
                    this.$notify({
                        title: "成功",
                        message: "保存成功",
                        type: "success",
                    });
                    // 保存成功之后历史治疗表格跳转，防止同一医嘱，多次保存，导致出现同一医嘱多个批次
                    this.judgeJumpMode();

                    // 保存完成之后，保存这次医嘱列表的Id,当提交时该数组和提交时抽取的数组不相同，则提示需要保存之后才可以提交
                    this.treatmentIdList = treatmentAdviceList.map(item => item.treatmentId);
                    this.$router.replace({
                        name: "medicalAdvice",
                        params: { batchId: response.content.batchId },
                    });
                })
                .catch((error) => {
                    console.log(error);
                });
        },

        //点击提交
        clickSubmit() {
            let list = this.treatmentAdviceList.map((item) => item.treatmentId);
            if (this.arraysAreEqual(list, this.treatmentIdList)) {
                commitCureBilling(this.batchIdData)
                    .then((response) => {
                        this.$notify({
                            title: "成功",
                            message: "提交成功",
                            type: "success",
                        });
                        this.$router.push("/outpatient/historyApply");
                    })
                    .catch((error) => {
                        console.log(error);
                    });
            } else {
                this.$notify({
                    title: "提示",
                    message: "请先保存，再提交",
                    type: "warning",
                });
            }
        },

        //点击评估
        clickAssess(row) {
            if (!this.batchIdData.batchId) {
                this.$notify({
                    title: "提示",
                    message: "请先保存后再进行评估",
                    type: "warning",
                });
                return;
            }else{
                let list = this.treatmentAdviceList.map((item) => item.treatmentId);
                if (!this.arraysAreEqual(list, this.treatmentIdList)){
                    this.$notify({
                        title: "提示",
                        message: "请先保存后再进行评估",
                        type: "warning",
                    });
                    return;
                }
            }
            let target = assessList.find((item) => item.type == row.estimateId);
            if(target){
                this.$router.push({
                    name: target.editRoute,
                    query: { type: 0, source: 2, id: this.batchId },
                });
            } else {
                console.log("请更新表")
            }
        },

        //点击详情
        clickDetail(row) {
            let list = this.treatmentAdviceList.map((item) => item.treatmentId);
            if (!this.arraysAreEqual(list, this.treatmentIdList)){
                this.$notify({
                    title: "提示",
                    message: "请先保存后再查看详情",
                    type: "warning",
                });
                return;
            }

            let target = assessList.find((item) => item.type == row.estimateId);
            this.$router.push({
                name: target.detailRoute,
                query: { type: 1, source: 1, id: this.batchId },
            });
        },

        //当从历史治疗申请的修改按钮进入时
        judgeJumpMode() {
            this.fromHistory = true;
            if (this.$route.params.batchId) {
                let batchId = this.$route.params.batchId;
                if (!batchId || batchId == ":batchId") {
                    return;
                }
                sendAdviceQuery(this.batchId).then((res) => {
                    this.patientInfo = res.content.patientInfo;
                    this.treatmentAdviceList = res.content.adviceList;
                    this.ReTreatmentAdviceList = res.content.adviceList; // 保存历史治疗申请传递过来的原始治疗项目明细
                    this.treatmentIdList = res.content.adviceList.map((item) => {
                        return item.treatmentId;
                    });
                    this.estimateList = res.content.estimateList;
                    this.ReEstimateList = res.content.estimateList; // 保存历史治疗申请传递过来的原始治疗评估
                    this.totalMoney = res.content.totalAmount;
                    this.adviceTime = res.content.adviceTime;
                    if (res.content.treatmentInformedInfo != null) {
                        this.treatmentInformedInfo = res.content.treatmentInformedInfo;
                        this.treatmentInformedInfo.isSave = true;
                    }
                    if (res.content.adviceHyperbaricOxygen != null) {
                        this.adviceHyperbaricOxygen = res.content.adviceHyperbaricOxygen;
                        this.adviceHyperbaricOxygen.isSave = true;
                    }
                    this.batchIdData.batchId = batchId;
                    // this.cureItemDetailFilter();
                    //判断是否显示知情同意书和操仓医嘱
                    this.showZQTYSOrCCYZ = this.treatmentAdviceList.find(
                        (item) => item.highOxygenStates == 1
                    )
                        ? true
                        : false;
                });
            }
        },
        formatGender(row, column, cellValue, index) {
            return cellValue === 0 ? '女' : cellValue === 1 ? '男' : cellValue;
        }
    },
    watch: {
        searchText: {
            handler() {
                if (this.searchText == '') {
                    this.singleOrPlan ? this.getCureSingle() : this.getCurePlan()
                }
            }
        },
        treatmentAdviceList: {
            handler() {
                let total = this.treatmentAdviceList.reduce(
                    (prev, next) =>
                    (prev +=
                        next.periodNum *
                        next.exePeriod *
                        next.unitPrice *
                        next.singleNum),
                    0
                );
                this.totalMoney = total.toFixed(2);
            },
            deep: true,
        },
    },
    mounted() {
        this.judgeJumpMode();
        this.getPatientInfo();
        this.getAllPatientInfo();
        this.getItemType();
        this.getCureSingle();
        this.getCurePlan();
        if (!this.batchIdData.batchId) {
            let now = new Date();
            let hours = String(now.getHours()).padStart(2, "0");
            let minutes = String(now.getMinutes()).padStart(2, "0");
            this.adviceTime = `${hours}:${minutes}`;
        }
        this.adviceHyperbaricOxygen.doctorSign = "";
    },
    beforeDestroy() {
        // 在组件销毁之前执行清理工作
        this.$store.commit("setIsReviseBtn", false);
    },
};
</script>

<style lang='scss' scoped>
.app-container {
    background-color: #fff;
    padding-bottom: 0;

    .width-80 {
        width: 80px;
    }

    .width-120 {
        width: 120px;
    }

    .width-150 {
        width: 150px;
    }

    .width-180 {
        width: 180px;
    }

    /deep/ .el-dialog__body {
        padding-top: 0;
    }

    .head-container {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .head-info {
            display: flex;
            justify-content: start;
            align-items: center;

            .name {
                font-weight: 900;
            }

            .info {
                font-weight: 300;
                display: flex;
                justify-content: start;
                align-items: center;

                div {
                    margin-right: 12px;
                }
            }
        }

        .head-info>div {
            margin: 0 15px;
        }

        .head-btn {
            .el-button {
                margin: 0 10px;
            }
        }
    }

    .body {
        width: 100%;
        height: 800px;
        max-height: 800px;
        box-sizing: border-box;
        padding-bottom: 10px;
        border: 1px solid #ccc;
        display: flex;

        #PatientList {
            width: 200px;
            // background-color: red;
            border-right: 1px solid #ccc;
            .search-container {
                display: flex;
                align-items: center;
                padding: 5px;
            }
        }

        #left {
            width: 300px;
            padding: 5px 10px;

            .left-radio {
                width: 100%;
                margin-bottom: 10px;

                /deep/.el-radio-button {
                    width: 50%;

                    .el-radio-button__inner {
                        width: 100%;
                        height: 30px;
                    }
                }
            }

            .changeBtn {
                width: 280px;
                height: 30px;
                border: 1px solid #dcdfe6;
                border-radius: 5px;
                overflow: hidden;
                margin-bottom: 10px;

                button {
                    width: 50%;
                    height: 100%;
                    background-color: #fff;
                    font-size: 12px;
                    color: #333;
                    text-align: center;
                    line-height: 30px;
                    border: none;
                }

                .bg {
                    background-color: #1890ff;
                    color: #fff;
                }
            }

            .left-select {
                width: 100%;
                margin-bottom: 10px;
            }

            .left-search {
                display: flex;
                align-items: center;
                margin-bottom: 10px;

                .el-input {
                    margin-right: 5px;
                }
            }
        }

        #right {
            width: calc(100% - 500px);
            padding: 5px 10px;
            border-left: 1px solid #ccc;

            #right-top {
                width: 100%;
                border-bottom: 1px solid #ccc;
                margin-bottom: 20px;

                :deep(.el-input__inner) {
                    text-align: center;
                }

                #right-top-info {
                    height: 38px;
                    padding: 0 0 10px;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;

                    i {
                        font-style: normal;
                        color: red;
                    }
                }
            }

            #right-down {
                width: 100%;

                .el-link {
                    margin: 0 10px;
                }

                #right-down-info {
                    height: 38px;
                    padding: 0 0 10px;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                }
            }
        }
    }
}
</style>
